package com.todo.strategy.online.application.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.todo.common.common.enums.BizErrorCodeEnum;
import com.todo.common.common.exception.BizException;
import com.todo.component.redis.RedisService;
import com.todo.strategy.common.constant.StrategyOnlineKeyBuild;
import com.todo.strategy.online.application.convert.MemoTemplateConvert;
import com.todo.strategy.online.application.entity.bo.MemoUserRelationBO;
import com.todo.strategy.online.application.service.MemoUserRelationService;
import com.todo.strategy.online.infrastructure.entity.domain.MemoUserRelationDO;
import com.todo.strategy.online.infrastructure.repository.MemoUserRelationRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author azhebuxing
 * @date 2024/11/29 00:32
 * @description
 */
@Slf4j
@Service
public class MemoUserRelationServiceImpl implements MemoUserRelationService {

    @Resource
    private MemoUserRelationRepository memoUserRelationRepository;
    @Resource
    private RedisService redisService;

    @Override
    public Boolean insertMemoUserRelation(MemoUserRelationBO memoUserRelationBO) {
        if (memoUserRelationBO == null) {
            log.error("MemoUserRelationService#insertMemoUserRelation 插入备忘录关联信息失败，入参异常");
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        MemoUserRelationBO alreadyMemoUserRelationBO = queryMemoUserRelationByUserPlanId(memoUserRelationBO.getUserId(), memoUserRelationBO.getPlanId());
        if (alreadyMemoUserRelationBO != null) {
            log.info("MemoUserRelationService#insertMemoUserRelation 插入备忘录关联信息完成，当前数据已经存在 userId:{}, planId:{}", memoUserRelationBO.getUserId(), memoUserRelationBO.getPlanId());
            throw new BizException(BizErrorCodeEnum.MEMO_RELATION_FAILED, "已经存在关联数据");
        }
        if (memoUserRelationBO.getContent() == null) {
            log.error("MemoUserRelationService#insertMemoUserRelation 插入备忘录关联信息失败，入参缺失");
            return false;
        }
        MemoUserRelationDO memoUserRelationDO = MemoTemplateConvert.convertToMemoUserRelationDO(memoUserRelationBO);
        boolean insert = memoUserRelationRepository.insertMemoUserRelation(memoUserRelationDO);
        if (insert) {
            String detailKey = StrategyOnlineKeyBuild.memoUserDetailKey(memoUserRelationDO.getId());
            redisService.set8H(detailKey, JSONObject.toJSONString(memoUserRelationBO));
            String relationKey = StrategyOnlineKeyBuild.memoUserPlanRelationKey(memoUserRelationBO.getUserId(), memoUserRelationBO.getPlanId());
            redisService.set8H(relationKey, String.valueOf(memoUserRelationDO.getId()));
        }
        log.info("MemoUserRelationService#insertMemoUserRelation 插入备忘录关联信息完成，入参:{}，结果：{}", JSONObject.toJSONString(memoUserRelationBO), insert);
        return insert;
    }

    @Override
    public Boolean updateMemoUserRelation(MemoUserRelationBO memoUserRelationBO) {
        if (memoUserRelationBO == null) {
            log.error("MemoUserRelationService#updateMemoUserRelation 更新备忘录关联信息失败，入参异常");
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        MemoUserRelationBO alreadyData = queryMemoUserRelationById(memoUserRelationBO.getId());
        if (alreadyData == null) {
            log.error("MemoUserRelationService#updateMemoUserRelation 更新备忘录关联信息完成，当前数据已经不存在 memoUserRelationBO:{}", JSONObject.toJSONString(memoUserRelationBO));
            throw new BizException(BizErrorCodeEnum.MEMO_RELATION_FAILED, "数据不存在");
        }
        MemoUserRelationDO memoUserRelationDO = MemoTemplateConvert.convertToMemoUserRelationDO(memoUserRelationBO);
        boolean update = memoUserRelationRepository.updateMemoUserRelationById(memoUserRelationDO);
        if (update) {
            String detailKey = StrategyOnlineKeyBuild.memoUserDetailKey(memoUserRelationDO.getId());
            redisService.del(detailKey);
        }
        log.info("MemoUserRelationService#updateMemoUserRelation 更新备忘录关联信息完成，入参:{}，结果：{}", JSONObject.toJSONString(memoUserRelationBO), update);
        return update;
    }

    @Override
    public Boolean removeMemoUserRelationById(Long id) {
        if (id == null || id < 0) {
            log.error("MemoUserRelationService#removeMemoUserRelationById 根据主键Id删除备忘录关联信息失败，入参异常");
            throw new BizException(BizErrorCodeEnum.PARAM_ERROR);
        }
        MemoUserRelationBO alreadyData = queryMemoUserRelationById(id);
        if (alreadyData == null) {
            log.info("MemoUserRelationService#removeMemoUserRelationById 根据主键Id删除备忘录关联信息完成，当前数据已经不存在 id:{}", id);
            return true;
        }
        boolean removed = memoUserRelationRepository.removeMemoUserRelationById(id);
        if (removed) {
            String detailKey = StrategyOnlineKeyBuild.memoUserDetailKey(id);
            redisService.del(detailKey);
            String relationKey = StrategyOnlineKeyBuild.memoUserPlanRelationKey(alreadyData.getUserId(), alreadyData.getPlanId());
            redisService.del(relationKey);
        }
        log.info("MemoUserRelationService#removeMemoUserRelationById 根据主键Id删除备忘录关联信息完成，入参:{}，结果：{}", id, removed);
        return removed;
    }

    @Override
    public MemoUserRelationBO queryMemoUserRelationById(Long id) {
        if (id == null || id < 0) {
            log.error("MemoUserRelationService#queryMemoUserRelationById 根据主键Id查询备忘录关联信息失败，入参异常");
            return null;
        }
        String detailKey = StrategyOnlineKeyBuild.memoUserDetailKey(id);
        if (redisService.hasKey(detailKey)) {
            MemoUserRelationBO memoUserRelationBO = JSONObject.parseObject(redisService.get(detailKey), MemoUserRelationBO.class);
            log.info("MemoUserRelationService#queryMemoUserRelationById 缓存根据主键Id查询备忘录关联信息完成，id:{}，结果:{}", id, JSONObject.toJSONString(memoUserRelationBO));
            return memoUserRelationBO;
        }
        MemoUserRelationDO memoUserRelationDO = memoUserRelationRepository.queryMemoUserRelationById(id);
        MemoUserRelationBO memoUserRelationBO = MemoTemplateConvert.convertToMemoUserRelationBO(memoUserRelationDO);
        if (memoUserRelationBO == null) {
            return null;
        }
        redisService.set8H(detailKey, JSONObject.toJSONString(memoUserRelationBO));
        String relationKey = StrategyOnlineKeyBuild.memoUserPlanRelationKey(memoUserRelationBO.getUserId(), memoUserRelationBO.getPlanId());
        redisService.set8H(relationKey, String.valueOf(memoUserRelationBO.getId()));
        log.info("MemoUserRelationService#queryMemoUserRelationById 数据库根据主键Id查询备忘录关联信息完成，id:{}，结果:{}", id, JSONObject.toJSONString(memoUserRelationBO));
        return memoUserRelationBO;
    }

    @Override
    public MemoUserRelationBO queryMemoUserRelationByUserPlanId(Long userId, Long planId) {
        if (userId == null || userId < 0 || planId == null || planId < 0) {
            log.error("MemoUserRelationService#queryMemoUserRelationByUserPlanId 根据用户id和计划id查询备忘录关联信息失败，入参异常");
            return null;
        }
        String relationKey = StrategyOnlineKeyBuild.memoUserPlanRelationKey(userId, planId);
        if (redisService.hasKey(relationKey)) {
            MemoUserRelationBO memoUserRelationBO = queryMemoUserRelationById(Long.valueOf(redisService.get(relationKey)));
            log.info("MemoUserRelationService#queryMemoUserRelationByUserPlanId 缓存根据用户id和计划id查询备忘录关联信息完成，userId:{},planId:{},结果:{}", userId, planId, JSONObject.toJSONString(memoUserRelationBO));
            return memoUserRelationBO;
        }
        MemoUserRelationDO memoUserRelationDO = memoUserRelationRepository.queryMemoUserRelationByUserIdAndPlanId(userId, planId);
        MemoUserRelationBO memoUserRelationBO = MemoTemplateConvert.convertToMemoUserRelationBO(memoUserRelationDO);

        if (memoUserRelationBO == null) {
            log.warn("MemoUserRelationService#queryMemoUserRelationByUserPlanId 数据库根据用户id和计划id查询备忘录关联信息完成，数据为空，userId:{},planId:{}", userId, planId);
            return null;
        }
        String detailKey = StrategyOnlineKeyBuild.memoUserDetailKey(memoUserRelationBO.getId());
        redisService.set8H(detailKey, JSONObject.toJSONString(memoUserRelationBO));
        redisService.set8H(relationKey, String.valueOf(memoUserRelationBO.getId()));
        log.info("MemoUserRelationService#queryMemoUserRelationByUserPlanId 数据库根据用户id和计划id查询备忘录关联信息完成，userId:{},planId:{},结果:{}", userId, planId, JSONObject.toJSONString(memoUserRelationBO));
        return memoUserRelationBO;
    }

    @Override
    public Boolean removeMemoUserRelationByUserPlanId(Long userId, Long planId) {
        if (userId == null || userId < 0 || planId == null || planId < 0) {
            log.error("MemoUserRelationService#removeMemoUserRelationByUserPlanId 根据用户id和计划id删除备忘录关联信息失败，入参异常");
            return null;
        }
        MemoUserRelationBO memoUserRelationBO = queryMemoUserRelationByUserPlanId(userId, planId);
        if (memoUserRelationBO == null) {
            return true;
        }
        boolean removed = memoUserRelationRepository.removeMemoUserRelationByUserIdAndPlanId(userId, planId);
        if (removed) {
            String detailKey = StrategyOnlineKeyBuild.memoUserDetailKey(memoUserRelationBO.getId());
            redisService.del(detailKey);
            String relationKey = StrategyOnlineKeyBuild.memoUserPlanRelationKey(userId, planId);
            redisService.del(relationKey);
        }
        log.info("MemoUserRelationService#removeMemoUserRelationByUserPlanId 根据用户id和计划id删除备忘录关联信息完成，userId:{},planId:{}，结果：{}", userId, planId, removed);
        return removed;
    }
}
